package cn.ex.org.service.impl;

import cn.ex.basic.service.impl.BasicServiceImpl;
import cn.ex.org.domain.Department;
import cn.ex.org.mapper.DepartmentMapper;
import cn.ex.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZeWangmu
 * @Date: 2022/06/01/14:20
 * @Description:
 */
@Service
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements IDepartmentService {
   @Autowired
   private DepartmentMapper deptMapper;

    @Override
    public void update(Department department) {
        deptMapper.update(department);
        this.save(department);
    }

    /**
     * 拼接dirPath
     * @param department
     */
    @Override
    public void save(Department department) {
        String dirPath = "";
        //如果父级id为空，则为第一级
        if(department.getParent_id() == null){
            dirPath = "/" + department.getId();
        }else{  //否则不是一级部门，根据Parent_id查询父级在拼接dirPath
            Department parents = deptMapper.loadById(department.getParent().getId());
            dirPath =  parents.getDirPath() + "/" + department.getId();
        }
        department.setDirPath(dirPath);
        deptMapper.update(department);
    }

    /**
     * 无限级树
     * @return
     */
    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public List<Department> searchTree() {
        //先查询所有
        List<Department> departments = deptMapper.loadAll();
        //用io流转为map集合，key = id ,vaule = department
       // Map<Long, Department> deptMap = departments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        Map<Long,Department> deptMap = new HashMap<>();
        for (Department department : departments) {
            deptMap.put(department.getId(),department);
        }
        //准备一个空集合用来装一级部门dept，里面含有所有子级查询到的数据
        List<Department> firstDepts = new ArrayList<>();
        for (Department temp : departments) {
            //如果Parent_id()为空，说明是一级部门
            if(temp.getParent_id() == null){
                firstDepts.add(temp);
            //否则就是子级部门
            }else{
                //找到上级,根据key = id 获取上级部门
                Department parent = deptMap.get(temp.getParent().getId());
                if(parent != null) {
                    //获取children集合并添加子级
                    parent.getChildren().add(temp);
                }
            }
        }
        return firstDepts;
    }
}
